package org.dromara.system.controller.gzh;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.json.utils.JsonUtils;
import org.dromara.system.domain.WxEeventType;
import org.dromara.system.domain.WxMessageType;
import org.dromara.system.domain.bo.GzhUserBo;
import org.dromara.system.domain.bo.XcxSubscribeKeywordBo;
import org.dromara.system.domain.bo.XcxSubscribeTemplateBo;
import org.dromara.system.domain.dto.TemplateMessage;
import org.dromara.system.domain.vo.GzhUserVo;
import org.dromara.system.domain.vo.XcxSubscribeTemplateVo;
import org.dromara.system.service.IGzhUserService;
import org.dromara.system.service.IXcxSubscribeTemplateService;
import org.dromara.system.utils.GzhPushUtil;
import org.dromara.system.utils.WXPublicAccountHttpUtil;
import org.dromara.system.utils.WxMessageUtil;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.util.List;
import java.util.Map;

import static cn.dev33.satoken.SaManager.log;

@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/wx")
public class WxController {
    private final IGzhUserService gzhUserService;
    private final IXcxSubscribeTemplateService xcxSubscribeTemplateService;


    // 必须替换
    private static final String wxToken = "888888";

    @GetMapping("/token")
    public String doGetWx(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String echostr = null;
        //token验证代码段
        try{
            log.info("请求已到达，开始校验token");
            //这里对应的文档里面的几个参数，如果不清楚，请查看文档
            if (StringUtils.isNotBlank(request.getParameter("signature"))) {
                String signature = request.getParameter("signature");
                String timestamp = request.getParameter("timestamp");
                String nonce = request.getParameter("nonce");
                echostr = request.getParameter("echostr");
                log.info("signature[{}], timestamp[{}], nonce[{}], echostr[{}]", signature, timestamp, nonce, echostr);
                WxMpService SignUtil = new WxMpServiceImpl();
                if (SignUtil.checkSignature(signature, timestamp, nonce)) {
                    log.info("数据源为微信后台，将echostr[{}]返回！", echostr);
                    response.getOutputStream().println(echostr);
                    return echostr;
                }
            }
        }catch (IOException e){
            log.error("校验出错");
            e.printStackTrace();
        }
        return echostr;
    }
    /**
     * @return
     * @throws ServletException
     * @throws IOException
     *
     */
    @PostMapping("/token")
    public void doPostWx(HttpServletRequest request, HttpServletResponse response)  {

        try {
            request.setCharacterEncoding("UTF-8");
            response.setCharacterEncoding("UTF-8");

            Map<String, String> requestMap = WxMessageUtil.parseXml(request);
            log.info("解析====>{}", request);
            String messageType = requestMap.get("MsgType");
            log.info("微信类型===>{}", messageType);
            String eventType = requestMap.get("Event");
            // 发送方帐号（open_id）
            String openid = requestMap.get("FromUserName");
            // 公众帐号
            String toUserName = requestMap.get("ToUserName");
            // 消息类型
            String msgType = requestMap.get("MsgType");
            if (messageType.equals(WxMessageType.EVENT.getCode())) {
                //判断消息类型是否是事件消息类型
                log.info("公众号====>事件消息");
                log.info("openid:" + openid);
                log.info("Event:" + eventType);
                if (eventType.equals(WxEeventType.SUBSCRIBE.getCode())) {
                    log.info("公众号====>新用户关注");
                    // 获取接口调用凭证
                    String accessToken = GzhPushUtil.getToken();
                    // 构建获取用户的基本信息
                    JSONObject userString = GzhPushUtil.getUserString(accessToken, openid);
                    //存入数据库
                    String jsonString = JsonUtils.toJsonString(userString);
                    GzhUserBo gzhUserBo = JSONUtil.toBean(jsonString, GzhUserBo.class);
                    GzhUserVo gzhUserVo = gzhUserService.queryList1(gzhUserBo);
                    if (gzhUserVo == null){
                        // 获取union_id
                        String unionID = GzhPushUtil.getUnionID(accessToken, openid);
                        gzhUserBo.setUnionid(unionID);
                        gzhUserService.insertByBo(gzhUserBo);
                    }else {
                        gzhUserBo.setId(gzhUserVo.getId());
                        gzhUserService.updateByBo(gzhUserBo);
                    }
                    TemplateMessage templateMessage = new TemplateMessage();
                    templateMessage.setTouser(openid);
                    //模板id
                    XcxSubscribeTemplateBo xcxSubscribeTemplateBo = new XcxSubscribeTemplateBo();
                    xcxSubscribeTemplateBo.setUsageScenarios("欢迎语");
                    List<XcxSubscribeTemplateVo> xcxSubscribeTemplateVos = xcxSubscribeTemplateService.queryList(xcxSubscribeTemplateBo);
                    templateMessage.setTemplate_id(xcxSubscribeTemplateVos.get(0).getTemplateId());
                    templateMessage.setTopcolor("#FF0000");
                    //给新关注的用户发送消息
                    WXPublicAccountHttpUtil.sendMessage(GzhPushUtil.getToken(),templateMessage);
                } else if (eventType.equals(WxEeventType.UNSUBSCRIBE.getCode())) {
                    // 获取接口调用凭证
                    String accessToken = GzhPushUtil.getToken();
                    // 构建获取用户的基本信息
                    JSONObject userString = GzhPushUtil.getUserString(accessToken, openid);
                    System.out.println(userString.toString());
                    //修改用户状态
                    String jsonString = JsonUtils.toJsonString(userString);
                    GzhUserBo gzhUserBo = JSONUtil.toBean(jsonString, GzhUserBo.class);
                    Long id = gzhUserService.queryList1(gzhUserBo).getId();
                    gzhUserBo.setId(id);
                    gzhUserService.updateByBo(gzhUserBo);

                    log.info("公众号====>用户取消关注");
                } else {
                    log.info("微信类型===>{}", messageType);
                    log.info("公众号===>其他");
                }
            } else if (messageType.equals(WxMessageType.TEXT.getCode())) {

            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }
}
